import { Provide } from '@midwayjs/core'
import { Repository } from 'typeorm'
import { InjectEntityModel } from '@midwayjs/typeorm'
import { Material } from '../../entities/Material.entity'

// 定义物资选项类型
interface MaterialOption {
  label: string | null;
  value: number;
}

@Provide()
export class MaterialService {
  @InjectEntityModel(Material)
  repo!: Repository<Material>

  async list(page: number = 1, pageSize: number = 10) {
    const [data, total] = await this.repo.findAndCount({
      skip: (page - 1) * pageSize,
      take: pageSize,
      order: { id: 'DESC' } // 可选排序
    })

    return {
      total,
      items: data,
    }
  }

  async add(data: Partial<Material>) {
    const obj = this.repo.create(data)
    return this.repo.save(obj)
  }

  async edit(data: Partial<Material>) {
    return this.repo.save(data)
  }

  async delete(id: number) {
    return this.repo.delete(id)
  }

  // 获取所有物资选项（名称和ID）
  async getOptions(): Promise<MaterialOption[]> {
    const materials = await this.repo.find({
      select: ['id', 'name'],
      order: { id: 'ASC' }
    });
    
    // 转换为label-value格式
    return materials.map(material => ({
      label: material.name,
      value: material.id
    }));
  }
}
